package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeCreateException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //字符串 --- > 字节数组 (<string>.getBytes)
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //密码变为暗文,再与数据库的暗文密码进行对比
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加用户
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Integer countByUsername = employeeMapper.selectCountByUsername(employeeDTO.getUsername());
        if(countByUsername>0){
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        //判断手机号是否合法
        checkEmployee(employeeDTO);

        Employee employee = new Employee();
        //注意,改工具类是在 employee的属性包含employeeDTO的属性,且属性名是一样的
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setStatus(StatusConstant.ENABLE);
        //数据库密码加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //todo  后期改为当前登录用户id
        //修改后
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        employeeMapper.insert(employee);
    }

    /**
     * 检查员工
     * @param employeeDTO
     */
    private void checkEmployee(EmployeeDTO employeeDTO) {
        if(Objects.isNull(employeeDTO.getPhone()) || employeeDTO.getPhone().length() != 11){
            throw new EmployeeCreateException(MessageConstant.ERROR_PHONE);
        }
        if(Objects.isNull(employeeDTO.getIdNumber()) || employeeDTO.getIdNumber().length() != 18){
            throw new EmployeeCreateException(MessageConstant.ERROR_ID_NUMBER);
        }
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.selectByNme(employeePageQueryDTO.getName());
        PageInfo<Employee> pageInfo = PageInfo.of(employeeList);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 更新状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        //修改最后操作时间和修改状态,最后修改人
        //修改状态,最后修改人交给AOP注解帮我们加
        Employee employee = employeeMapper.selectById(id);

        //修改状态
        employee.setStatus(status);

        //修改 --- update
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public Employee queryById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword(null);
        log.info("{}",employee);
        return employee;
    }

    /**
     * 更新员工
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Integer count = employeeMapper.selectByUsernameNotSelf(employeeDTO.getUsername(),employeeDTO.getId());
        if(count>0){
            throw new EmployeeCreateException(MessageConstant.REPEAT_USER_NAME);
        }
        //检查员工
        this.checkEmployee(employeeDTO);

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeMapper.update(employee);
    }

}
